<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="`${isUpdate ? '编辑' : '新增'}账号`" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { changePasswordFormSchema } from './account.data';
  import {updateAdminUser, createAdminUser, changePassword} from "@/api/admin/admin_user";
  import {useMessage} from "@/hooks/web/useMessage";

  defineOptions({ name: 'AccountModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');
  const { createMessage } = useMessage()

  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: changePasswordFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    rowId.value = data.record.id;
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      const { password, password1 } = values;
      if(password != password1){
        createMessage.warning(`两次键入的密码不一致`);
        return false;
      }

      let response = await changePassword({ id: rowId.value, ...values });
      const { code, msg } = response;
      if (0 === code){
        createMessage.success(`修改成功！`);
      } else {
        createMessage.error(msg ? msg : `修改失败`);
      }
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
